package com.study.sgu.hsp.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @author study
 * @version 1.0
 * @date 2020/9/27 22:58
 */
public class NioServer {
    public static void main(String[] args) throws IOException {
        //创建ServerSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        //得到select对象
        Selector selector = Selector.open();

        //绑定端口在服务器监听
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        //设置非阻塞
        serverSocketChannel.configureBlocking(false);

        // serverSocketChannel注册 selector关系事件
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        //等待客户端连接
        while (true) {
            //等待1秒
            if (selector.select(1000) == 0) {
                //没有事件发生
                System.out.println("服务器等待了1S,无连接");
                continue;
            }
            //获取相关selectionkey集合
            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            Iterator<SelectionKey> keyiterator = selectionKeys.iterator();
            while (keyiterator.hasNext()) {
                //获取 selectionkey
                SelectionKey key = keyiterator.next();
                SelectableChannel channel = key.channel();
                //根据key做相应的处理
                if (key.isAcceptable()) {
                    //客户端来连接
                    // 该客户端生成一个socketChannle
                    SocketChannel socketChannel = serverSocketChannel.accept();

                    //设置为非阻塞
                    socketChannel.configureBlocking(false);
                    //
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if (key.isReadable()) {
                    //读操作
                    //通过key方向获取 对应channel
                    SocketChannel channel1 = (SocketChannel) key.channel();
                    //获取该channel关联的buffer
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    channel1.read(buffer);
                    System.out.println("from 客户端" + new String(buffer.array()));
                }
                //手动从集合中移除当前selectkey，防止重复操作
                keyiterator.remove();


            }


        }


    }
}
